import { md5 } from "@/util/md5";
import { apiAuthId, apiAuthSecret } from "@/config/config";
import { requestApi, catchException } from "@/util/request";

async function apiAuth(expireTime: string) {
  const timestamp = new Date().getTime();
  if (+expireTime - timestamp > 0) return {};
  const str = `${apiAuthId}${apiAuthSecret}${timestamp}`;
  const code = md5(str).toLocaleUpperCase();
  try {
    const invite_code = uni.getStorageSync("appInviteCode") || "";
    const res = await requestApi({
      url: "getToken",
      method: "POST",
      loading: false,
      data: { code, timestamp, app_invite_code: invite_code },
    });
    let { token, expires_in } = res.data.content;
    expires_in = timestamp + +expires_in * 1000;
    const apiToken = JSON.stringify({ token, expires_in });
    uni.setStorageSync("apiToken", apiToken);
    return { token, expires_in };
  } catch (error) {
    catchException(error);
  }
}

export { apiAuth };
